package com.CommunityHub.kiana.controller;
import com.CommunityHub.kiana.po.HouseInfo;
import com.CommunityHub.kiana.po.ResidenceInfo;
import com.CommunityHub.kiana.po.User;
import com.CommunityHub.kiana.service.MemberService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
@WebServlet("/ViewOccupantsServlet")
public class ViewOccupantsServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect("login.jsp");
            return;
        }

        User user = (User) session.getAttribute("user");
        int memberId = user.getId();
        MemberService memberService = new MemberService();
// 查询已购房产
        List<HouseInfo> purchasedHouses = null;
        try {
            purchasedHouses = memberService.getPurchasedHouses(memberId);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }

// 设置请求属性，供 editOccupant.jsp 使用
        request.setAttribute("purchasedHouses", purchasedHouses);
        // 获取房产ID参数（可选）
        String houseIdParam = request.getParameter("houseId");


        try {
            List<ResidenceInfo> occupants;

            if (houseIdParam != null && !houseIdParam.isEmpty()) {
                // 获取特定房产的入住人
                int houseId = Integer.parseInt(houseIdParam);
                occupants = memberService.getOccupantsByHouse(houseId);
            } else {
                // 获取会员的所有入住人
                occupants = memberService.getOccupants(memberId);
            }

            request.setAttribute("occupants", occupants);
            request.getRequestDispatcher("viewOccupants.jsp").forward(request, response);
        } catch (SQLException | NumberFormatException e) {
            request.setAttribute("error", "加载入住人失败: " + e.getMessage());
            request.getRequestDispatcher("viewOccupants.jsp").forward(request, response);
        }
    }
}
